package com.lunimei.container;

import java.io.File;
import java.io.IOException;

import org.apache.catalina.Context;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.startup.Tomcat;

import com.lunimei.servlet.StopServerServlet;
import com.lunimei.servlet.VersionServlet;
import com.lunimei.utils.MLog;

public class CatalinaContainer {
	private CatalinaContainer() {
	}

	private static final String TAG = "CatalinaContainer";
	private static CatalinaContainer instance;
	private Tomcat tomcat;

	public static CatalinaContainer getInstance() {
		if (instance == null) {
			instance = new CatalinaContainer();
			instance.init();
		}
		return instance;
	}

	private void init() {
		tomcat = new Tomcat();
		tomcat.setPort(8090);

		File base = new File(".\\runtime\\.");
		String basedir = base.getAbsolutePath();
		if (!base.exists()) {
			MLog.i(TAG, "create base dir: " + basedir);
			base.mkdir();
		}
		MLog.d(TAG, "set base dir: " + basedir);
		tomcat.setBaseDir(basedir);

		Context ctx = tomcat.addContext("/", basedir);
		Tomcat.addServlet(ctx, "Version", new VersionServlet());
		ctx.addServletMapping("/version", "Version");
		Tomcat.addServlet(ctx, "StopServerSevlet", new StopServerServlet());
		ctx.addServletMapping("/stop", "StopServerSevlet");
	}

	public void start() {
		try {
			tomcat.start();
		} catch (LifecycleException e) {
			MLog.e(TAG, "cannot start Tomcat", e);
		}
		tomcat.getServer().await();
	}

	public void stop() {
		try {
			tomcat.stop();
		} catch (LifecycleException e) {
			MLog.e(TAG, "cannot stop Tomcat", e);
		}
	}
}
